package com.zhika.zishi.fragments.login;

import android.animation.ObjectAnimator;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zhika.zishi.MyApplication;
import com.zhika.zishi.R;
import com.zhika.zishi.constant.InternetConstant;
import com.zhika.zishi.constant.OthersConstant;
import com.zhika.zishi.customview.OtherWayView;
import com.zhika.zishi.db.OperateDb;
import com.zhika.zishi.db.datas.UserData;
import com.zhika.zishi.interfaces.OtherWayInterface;
import com.zhika.zishi.internet.PostInternet;
import com.zhika.zishi.util.LogUtil;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.json.JSONStringer;

import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by Michael on 2015/4/3.
 */
public class RegisterFragment extends Fragment implements View.OnClickListener, OtherWayInterface {

    private static final String TAG = "RegisterActivity";
    //注册页面2的布局
    private LinearLayout identify2Layout;

    //注册也页面1的布局
    private LinearLayout identify1Layout;

    //注册布局1的高度
    private int identify1Height;

    //注册布局的顶边距
    private int identify1TopMargin;

    private RelativeLayout.LayoutParams identify1Params;

    private Button sendIdentifyButton;

    private Button loginButton;
    private Button loginBu;

    private OtherWayView otherWayRegisterView;

    private TextView identifyTimeText;

    private Timer timer;

    private TimerTask timerTask;

    //验证码的有效时间（秒）
    private int timeCount = 10;

    //手机号
    private EditText phoneEdit;
    private String telephone;

    //密码
    private EditText passwordEdit;
    private String password;

    //验证码
    private EditText identifyEdit;
    private String identifyCode;

    //昵称
    private EditText nicknameEdit;
    private String nickname;

    private Button registerButton;

    //更新验证码的有效时间
    private static final int IDENTIFY_CODE = 0;

    //注册是否成功
    private static final int REGISTER_SUCCESS = 1;

    //该界面的view
    private View view;

    //上下文
    private Context context;

    //单例模式下的Fragment
    private static RegisterFragment registerFragment;

    //男
    private TextView manText;

    //女
    private TextView womanText;

    //性别：2--null  1--男  0--女；默认：null
    private int currentSex = 2;

    //操作数据库SQLite
    private OperateDb operateDb;

    /**
     * 根据传过来的信息，更新UI
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                //更新验证码的有效时间
                case IDENTIFY_CODE:
                    identifyTimeText.setText(timeCount + "秒后重新获取");

                    if (timeCount == 0) {
                        if (timer != null) {
                            timer.cancel();
                        }
                        if (timerTask != null) {
                            timerTask.cancel();
                        }
                        identifyTimeText.setText("重获验证码");
                        identifyTimeText.setClickable(true);
                        identifyTimeText.setBackground(getResources().getDrawable(R.drawable.identify_focus_shape));
                    }
                    break;
                case REGISTER_SUCCESS:
                    int is = msg.arg1;
                    if (is == 1){
                        showToast("注册成功");
                        ((OnRegisterListener) context).register();
                    }else {
                        showToast("注册失败");
                    }
                    resetWidget();
                    break;

                case OthersConstant.SEND_IDENTIFY_CODE_HANDLER:

                    //发送验证码成功
                    if (msg.arg1==1){
                    }
                    //发送验证码失败
                    else {
                        String errorStr = (String) msg.obj;
                        MyApplication.showToast(errorStr);
                        LogUtil.e(TAG,"发送验证码失败");
                    }
                    break;

            }
        }
    };

    /**
     * 在activity中实现此接口的方法，控制该fragment的事件
     */
    public interface OnRegisterListener {

        //注册界面中，登录按钮的事件
        public void registerLogin();

        //注册按钮的事件
        public void register();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.register_layout, container, false);

        initView();

        getLayoutHeight();

        return view;

    }

    @Override
    public void onResume() {
        super.onResume();
        resetWidget();
    }

    /**
     * 重置所有可编辑控件的内容
     */
    private void resetWidget() {
        identifyEdit.setText("");
        passwordEdit.setText("");
        nicknameEdit.setText("");
    }

    /**
     * 初始化界面的控件
     */
    private void initView() {

        context = getActivity();

        operateDb = new OperateDb(context);

        identify1Layout = (LinearLayout) view.findViewById(R.id.register_identify_1_layout);
        identify1Params = (RelativeLayout.LayoutParams) identify1Layout.getLayoutParams();
        identify2Layout = (LinearLayout) view.findViewById(R.id.register_identify_2_layout);
        sendIdentifyButton = (Button) view.findViewById(R.id.register_send_identify_button);
        sendIdentifyButton.setOnClickListener(this);

        loginButton = (Button) view.findViewById(R.id.register_1_login_button);
        loginButton.setOnClickListener(this);
        loginBu = (Button) view.findViewById(R.id.register_login_button);
        loginBu.setOnClickListener(this);

        otherWayRegisterView = (OtherWayView) view.findViewById(R.id.register_other_way_view);
        otherWayRegisterView.setOtherWayInterface(this);

        identifyTimeText = (TextView) view.findViewById(R.id.register_identify_time_text);
        identifyTimeText.setOnClickListener(this);

        phoneEdit = (EditText) view.findViewById(R.id.register_phone_text);
        phoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    sendIdentifyButton.setBackground(getResources().getDrawable(R.drawable.yellow_edging_shape));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        registerButton = (Button) view.findViewById(R.id.register_button);
        registerButton.setOnClickListener(this);

        identifyEdit = (EditText) view.findViewById(R.id.register_identify_code_text);

        passwordEdit = (EditText) view.findViewById(R.id.register_password_edit);

        nicknameEdit = (EditText) view.findViewById(R.id.register_nickname_edit);
        nicknameEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 && currentSex != 2) {
                    registerButton.setBackground(getResources().getDrawable(R.drawable.yellow_edging_shape));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        manText = (TextView) view.findViewById(R.id.register_man_text);
        manText.setOnClickListener(this);

        womanText = (TextView) view.findViewById(R.id.register_woman_text);
        womanText.setOnClickListener(this);

    }

    /**
     * 获取注册布局1的高度
     */
    private void getLayoutHeight() {
        identify1Layout.post(new Runnable() {
            @Override
            public void run() {
                identify1Height = identify1Layout.getHeight();
                identify1TopMargin = identify1Params.topMargin;
                LogUtil.e(TAG, "注册页面1的顶边距：" + identify1TopMargin);
                LogUtil.e(TAG, "注册页面1的高度：" + identify1Height);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (context instanceof OnRegisterListener) {
            switch (v.getId()) {
                case R.id.register_send_identify_button:
                    sendIdentifyButtonListener("send");
                    break;
                case R.id.register_1_login_button:
                case R.id.register_login_button:
                    ((OnRegisterListener) context).registerLogin();
                    break;
                case R.id.register_identify_time_text:
                    sendIdentifyButtonListener("again");
                    break;
                case R.id.register_button:
                    registerButtonListener();
                    break;
                case R.id.register_man_text:

                    //设置当前的性别是男
                    currentSex = 1;
                    sexTextListener(manText, womanText);
                    break;
                case R.id.register_woman_text:

                    //设置当前的性别是女
                    currentSex = 0;
                    sexTextListener(womanText, manText);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 性别按钮的功能
     */
    private void sexTextListener(TextView text1, TextView text2) {
        text1.setBackgroundColor(getResources().getColor(R.color.color_red));
        text1.setTextColor(getResources().getColor(R.color.color_black));

        text2.setBackgroundColor(getResources().getColor(R.color.identify_false_color));
        text2.setTextColor(getResources().getColor(R.color.color_white));

    }

    /**
     * 更新验证码的有效时间，并发送验证码
     */
    private void updateIdentifyTime() {

        //发送验证码
        PostInternet.sendIdentifyCode(telephone, context, handler);

        identifyTimeText.setBackground(getResources().getDrawable(R.drawable.identify_no_shape));
        identifyTimeText.setClickable(false);
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (handler != null) {
                    Message message = Message.obtain(handler, IDENTIFY_CODE);
                    handler.sendMessage(message);
                }

                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                timeCount--;

            }
        };
        timer.schedule(timerTask, 1000, 1000);

    }

    /**
     * 发送验证码的事件
     * type 判断是第一次发送还是重新发送验证码
     * send：第一次发送
     * again: 重新发送
     */
    private void sendIdentifyButtonListener(String type) {
        if (checkPhoneSex()) {

            //隐藏软键盘
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(phoneEdit.getWindowToken(), 0);

            //如果是第一次发送验证码
            if (type.equals("send")) {
                identify2Layout.setVisibility(View.VISIBLE);

                //属性动画，沿Y轴向下移动
                ObjectAnimator.ofFloat(identify1Layout, "translationY", 0, identify1Height).setDuration(500).start();
            }

            updateIdentifyTime();
        }
    }


    @Override
    public void weixinButtonListener() {
        Toast.makeText(context, "微信注册", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void sinaButtonListener() {
        Toast.makeText(context, "新浪微博注册", Toast.LENGTH_SHORT).show();

    }

    /**
     * 注册按钮的事件
     */
    private void registerButtonListener() {
        if (checkPhoneSex()) {
            identifyCode = identifyEdit.getText().toString();
            if (identifyCode == null || identifyCode.equals("")) {
                showToast("请输入验证码");
            } else {
                password = passwordEdit.getText().toString();
                if (password == null || password.equals("")) {
                    showToast("请输入密码");
                } else if (password.length() < 6) {
                    showToast("密码最少6位");
                } else {
                    nickname = nicknameEdit.getText().toString();
                    if (nickname == null || nickname.equals("")) {
                        showToast("请输入昵称");
                    } else {

                        //注册
                        registerInternet();
                    }
                }
            }
        }
    }

    /**
     * 实现注册功能
     */
    private void registerInternet() {
        String url = InternetConstant.SERVER_ADDRESS + InternetConstant.REGISTER;
        LogUtil.e(TAG,"url:"+url);

        try {

            //请求参数：  { "telephone": "13730650160", "code" :"831922", "passwd": "zs1234",
            //             "nickname":"治龙", "deviceTag":"testing", "sex":1 }
            JSONStringer stringer = new JSONStringer().object()
                    .key("telephone").value(telephone)
                    .key("code").value(identifyCode)
                    .key("passwd").value(password)
                    .key("nickname").value(nickname)
                    .key("deviceTag").value(MyApplication.device_id)
                    .key("sex").value(currentSex)
                    .endObject();
            StringEntity entity = new StringEntity(stringer.toString(), HTTP.UTF_8);
            LogUtil.e(TAG,"注册-请求参数："+stringer.toString());

            MyApplication.asyncHttpClient.post(context, url, entity, InternetConstant.CONTENT_TYPE, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String jsonData = new String(bytes);
                    LogUtil.e(TAG, "注册：code=" + i + ";" + "JsonData:" + jsonData);

                    //解析返回的数据
                    parseRegisterJson(jsonData);
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    LogUtil.e(TAG, "错误码：code=" + i);
                    throwable.printStackTrace();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 检验手机号的格式是不是正确,并检查是否已选择性别
     *
     * @return
     */
    private boolean checkPhoneSex() {
        if (currentSex == 2) {
            showToast("请选择性别");
            return false;
        } else {
            telephone = phoneEdit.getText().toString();
            if (telephone.equals("") || telephone == null) {
                showToast("请输入手机号");
                return false;
            } else if (telephone.length() != 11) {
                showToast("手机号格式不正确");
                return false;
            } else {

                return true;
            }
        }

    }

    /**
     * 设置Toast的信息
     *
     * @param msg
     */
    private void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 解析注册返回的json数据
     * @param jsonData
     */
    private void parseRegisterJson(String jsonData){
        if (jsonData!=null && !jsonData.equals("")){
            try{
                JSONObject jsonObject = new JSONObject(jsonData);
                boolean is = jsonObject.getBoolean("success");

                //通知主线程注册的结果
                Message message = Message.obtain();
                message.what = REGISTER_SUCCESS;

                //注册成功
                if (is){
                    message.arg1 = 1;
                }
                //注册失败
                else {
                    message.arg1 = 2;
                }
                handler.sendMessage(message);


                JSONObject paramObject = jsonObject.getJSONObject("param");
                int userId = paramObject.getInt("uid");
                String userNickname = paramObject.getString("nickname");
                String userToken = paramObject.getString("token");
                UserData user = new UserData();
                user.setUserId(userId);
                user.setNickname(userNickname);
                user.setUserToken(userToken);

                //将用户的数据插入用户表中
                operateDb.insertUser(user);

            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            LogUtil.e(TAG,"注册返回的数据是空的");
        }

    }
}
